// RSA – алгоритм шифрования с открытым ключом
#include <stdio.h>
#include <math.h>
#include <fstream>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include "rsa.h"

using namespace std;

int main (int argc, char * argv [])
{
	if (argc < 4)
	{
		cout << "The format of input data:" << endl;
		cout << "[action (c,d)] input_file.* output_file.*" << endl;
		return 1;
	}
	
	if (!strcmp(argv[1],"c"))
	{
		std::ifstream ifile (argv[2], std::ios::binary);
		std::ofstream ofile (argv[3], std::ios::binary);
		
		int * cbuff;
		char dbuff [256];
		if(!ifile.is_open() || !ofile.is_open()) 
			return 1;
		
		while (!ifile.eof())
		{
			ifile.getline (dbuff,256);
			cbuff = codeRsaMsg(dbuff,strlen (dbuff));
			for (int i(0); i< strlen (dbuff); i++)
			{
				if (i)
					ofile << ',' << cbuff[i];
				else
					ofile << cbuff[i];
			}
			delete [] cbuff;
			if (!ifile.eof())
				ofile << endl;
		}
		
		ifile.close();
		ofile.close();
	}
	else if (!strcmp(argv[1],"d"))
	{
		std::ifstream ifile (argv[2], std::ios::binary);
		std::ofstream ofile (argv[3], std::ios::binary);
		if(!ifile.is_open() || !ofile.is_open()) 
			return 1;
		
		int * cbuff;
		char * dbuff;
		unsigned long long fsize = 0;
		while (!ifile.eof())
		{
			char * buff = new char [256];
			int count = 0;
			ifile.getline (buff,256);
			for (int i = 0; i < strlen (buff); i++)
			{
				if (buff [i] == ',')
					count++;
			}
			count++;
			cbuff = new int [count+1];
			int i = 0;
			do
			{
				char * tmp = strsep(&buff,",");
				if (atoi(tmp))
					cbuff [i] = atoi(tmp);
				else
					break;
				i++;
			}
			while (buff);
			cbuff [i] = '\0';
			dbuff = decodeRsaMsg(cbuff,count+1);
			ofile << dbuff;
			if (!ifile.eof())
				ofile << endl;
			delete [] buff;
			delete [] dbuff;
			delete [] cbuff;
		}		
		ifile.close();
		ofile.close();
	}
	else
	{
		cout << "Error!!! The format of input data:" << endl;
		cout << "[action (c,d)] input_file.* output_file.*" << endl;
	}
	return 0;
}
